import 'package:get/get.dart';
import 'package:getx_tutorial/app/data/models/news_model.dart';
import 'package:getx_tutorial/app/data/providers/base_provider.dart';

abstract class INewsProvider {
  // 新闻列表
  Future<Response<NewsList>> getNewsList({
    String type = 'top', 
    int page = 1, 
    int page_size = 10
  });

  // 新闻详情
  Future<Response<NewsItem>> getNewsDetail(String uniquekey);
}

class NewsProvider extends BaseProvider implements INewsProvider {
  String key = "6d7ee8d88bd4fb137f5d20ce7066a700";

  @override
  void onInit() {
    super.onInit();

    // httpClient.defaultDecoder = (map) {
    //   if (map is Map<String, dynamic>) return NewsList.fromJson(map['result']);
    // };
  }

  // 新闻列表
  @override
  Future<Response<NewsList>> getNewsList({
    String type = 'top', 
    int page = 1, 
    int page_size = 10
  }) async {
    var response = await get("toutiao/index?type=${type}&page=$page&page_size=${page_size}&key=${key}");
    // print('=== Provider: ');
    // print(response);
    // print(response.body);
    var data = NewsList.fromJson(response.body['result']);
    return Response(
      statusCode: response.statusCode,
      statusText: response.statusText,
      body: data,
    );
  }

  // 新闻详情
  @override
  Future<Response<NewsItem>> getNewsDetail(String uniquekey) async {
    var response = await get("toutiao/content?uniquekey=${uniquekey}&key=${key}");
    // print('=== Provider - getNewsDetail: ');
    // print(response);
    // print(response.body);

    // 封装返回结果
    var data = NewsItem.fromJson({
      ...response.body['result']['detail'],
      "uniquekey": response.body['result']['uniquekey'],
      "content": response.body['result']['content'],
    });
    
    return Response(
      statusCode: response.statusCode,
      statusText: response.statusText,
      body: data,
    );
  }
}